#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include "EnableDebugPrivileges.h"

DWORD WINAPI ModifyMem(LPVOID p)
{
	char buff[64];

	//0055D39F - 8b 5c 88 08 - mov ebx,[eax+ecx*4+08]
	BYTE* ptrc = (BYTE*)0x0055D39F;
	
	BYTE toDetourCode[] = {0x2E, 0xFF, 0x25, 0xAA, 0xAA, 0xAA, 0xAA}; // jmp dword ptr cs:[0xAAAAAAAA]

	BYTE detourCode[] = 
	{
		//0x90, 0x90, 0x90, 0x2E, 0xC6, 0x05, 0x9F, 0xD3, 0x55, 0x00, 0x8B, 0x2E, 0xC6, 0x05, 0x40, 0xD3, 0x55, 0x00, 0x5C, 0x2E, 0xC6, 0x05, 0x41, 0xD3, 0x55, 0x00, 0x88, 0x2E, 0xC6, 0x05, 0x42, 0xD3, 0x55, 0x00, 0x08, 0x2E, 0xC6, 0x05, 0x43, 0xD3, 0x55, 0x00, 0x8B, 0x2E, 0xC6, 0x05, 0x44, 0xD3, 0x55, 0x00, 0x0B, 
		//0x2E, 0xC6, 0x05, 0x45, 0xD3, 0x55, 0x00, 0xA1, 
		//0x2E, 0xFF, 0x25, 0x9F, 0xD3, 0x55, 0x00, 0x90, 0x90, 0x90
		0xCC
	};
	
	DWORD oldProtect;
	void* detourMem = malloc(1024);

#ifdef _DEBUG
	__asm int 3;
#endif

	memcpy(detourMem, detourCode, sizeof(detourCode));

	EnableDebugPrivileges();

	VirtualProtect(detourMem, 1024, PAGE_EXECUTE_READWRITE, &oldProtect);
	VirtualProtect(ptrc, 32, PAGE_EXECUTE_READWRITE, &oldProtect);

	// Set the jmp address to the dyn mem where we store the new code
	*((void**)(toDetourCode+3)) = detourMem;

	memcpy(ptrc, toDetourCode, sizeof(toDetourCode));

	return 0;
}

BOOL APIENTRY DllMain(HANDLE module,
					  DWORD reason,
					  LPVOID reserved)
{
	if(reason == DLL_PROCESS_ATTACH)
		CreateThread(0, 0, ModifyMem, 0, 0, 0);
	return TRUE;
}